import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
// import qs from 'qs'
import { showMessage } from './status'
import { ElMessage } from 'element-plus'

const axiosInstance:AxiosInstance = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL
  // headers: {
  //   'Content-Type': 'application/x-www-form-urlencoded'
  // }
  // transformRequest: [
  //   function (data) {
  //     // 由于使用的 form-data传数据所以要格式化
  //     delete data.Authorization
  //     data = qs.stringify(data)
  //     return data
  //   }
  // ]
})

// axios实例拦截响应
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status === 200) {
      return response.data
    } else {
      showMessage(response.status)
      return response.data
    }
  },
  // 请求失败
  (error: AxiosError) => {
    console.log('error: ', error)
    const { response } = error
    if (response) {
      // 请求已发出，但是不在2xx的范围
      showMessage(response.status)
      return Promise.reject(response.data)
    } else {
      ElMessage.warning('网络连接异常,请稍后再试!')
    }
  }
)

// axios实例拦截请求
axiosInstance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

export default axiosInstance
